from .node import Node

# 递归法找到所有节点（节点的部分参数还没放进去），使用前先生成一个空的集合nodes，并以根节点作为element代入
def generate_node_hierarchy(nodes, element, failure_models,repair_models):
    root = Node('root')
    root.parent=None
    nodes.append(root)
    for model in element.find('models').findall('model'):
        model_node = Node(model.attrib["name"])
        nodes.append(model_node)
        for node in model:
            cnode = handle_model(node,nodes,failure_models,repair_models)
            cnode.is_sys = True
            model_node.children.append(cnode)
            cnode.parent = model_node
        root.children.append(model_node)
        model_node.parent = root 

        if model_node.is_basic:
            if model_node.parent.node_type in ["warm_standby"] :
                model_node.failure_rate = float(model.attrib["rate"])


def handle_model(model,all_nodes,failure_models,repair_models):
    ele = Node(model.attrib["name"])
    ele.node_type = model.attrib["type"]

    if model.tag == "logic":
        if ele.node_type in ["vote","standby","warm_standby"] :
            if 'k' in model.attrib:
                ele.kvalue = int(model.attrib["k"]) 
        for cnode in model:
            child = handle_model(cnode,all_nodes,failure_models,repair_models)
            ele.children.append(child)
            child.parent = ele
    elif model.tag == "node":
        if 'cycon' and 'cycdown' in model.attrib:
            ele.is_cyc = True
            ele.cyc[0] = float(model.attrib['cycon'])
            ele.cyc[1] = float(model.attrib['cycdown'])
        ele.status = 'on'
        ele.is_basic = True
        for fm in model:
            if fm.tag=="failure_model":
                ele.failure_dist = failure_models[fm.attrib["name"]]
            elif fm.tag=="repair_model":
                ele.repair_dist = repair_models[fm.attrib["name"]]
    all_nodes.append(ele)
    return ele
